package com.yfbao.horizon.schedule.tk.service;


import com.yfbao.horizon.schedule.tk.entity.TrxTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Service
@CacheConfig(cacheNames = "trxTask")
@Slf4j
public class TrxTaskService {

    @Lazy
    @Autowired
    private TrxTaskService self;

    @Cacheable
    public TrxTask selectById(Long id){
        TrxTask task =new TrxTask();
        task.setTrxId(id);
        task.setMethod("aaa");
        task.setParamData("bbb");
        System.out.println("new task:"+id);
        return task;
    }

    @Cacheable
    public TrxTask selectByIdNoCache(Long id){
        TrxTask trxTask = self.selectById(id);
        return trxTask;
    }


    @Transactional
    public void registAfterCommit() {

//        TransactionSynchronizationManager.registerSynchronization(
//                new TransactionSynchronization() {
//                    @Override
//                    public void afterCommit() {
//                        System.out.println("after commnit aaaa");
//                    }
//                }
//        );

        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            try {
                TransactionSynchronizationManager.registerSynchronization(
                        new TransactionSynchronization() {
                            @Override
                            public void afterCompletion(int status) {
                                if (status == TransactionSynchronization.STATUS_COMMITTED) {
                                    System.out.println("after commit aaaa");
                                } else {
                                    System.out.println(String.format("EventBus中事务提交失败,EventBus事件配置的不执行,若要开启请配置：[seeyon.eventbus.uncommit-execute=true]，事务状态status:{} ", status ));
                                }
                            }
                        });
            } catch (Exception e) {
                log.error("EventBus中事务已提交完成，继续执行eventbus：{}", e);

            }
        } else {
            System.out.println("not Transaction");
        }
    }
}
